package com.linkstec.concurrent;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
 
/**
 * @description: 延时队列
 * @author: LYL
 */
public class DelayedQueneTest {
 
    public static void main(String[] args) throws InterruptedException {
    	
    	Item del = new Item("item2",10, TimeUnit.SECONDS,"");
    	Item delnull = new Item("item2null",10, TimeUnit.SECONDS,"");
        Item item1 = new Item("item1", 5, TimeUnit.SECONDS,"");
        Item item2 = new Item("item2",10, TimeUnit.SECONDS,"");
        Item item3 = new Item("item3",15, TimeUnit.SECONDS,"");
        DelayQueue<Item> queue = new DelayQueue<>();
        queue.put(item1);
        queue.put(item2);
        queue.put(item3);
        queue.remove(del);
        queue.remove(delnull);
        System.out.println("begin time:" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        for (int i = 0; i < 3; i++) {
            Item take = queue.take();
            System.out.format("name:{%s}, time:{%s}\n",take.user_id, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }
    }
 
}
 
class Item implements Delayed{
    /* 触发时间*/
    private long time;
    String user_id;
    String current_step;
 
    public Item(String user_id, long time, TimeUnit unit, String current_step) {
    	this.time = System.currentTimeMillis() + (time > 0? unit.toMillis(time): 0);
        this.user_id = user_id;
        this.current_step = current_step;
    }
 
    @Override
    public long getDelay(TimeUnit unit) {
        return time - System.currentTimeMillis();
    }
 
    @Override
    public int compareTo(Delayed o) {
        Item item = (Item) o;
        long diff = this.time - item.time;
        if (diff <= 0) {// 改成>=会造成问题
            return -1;
        }else {
            return 1;
        }
    }
 
    @Override
    public String toString() {
        return "Item{" +
                "time=" + time +
                ", user_id='" + user_id + '\'' +
                '}';
    }

	@Override
	public boolean equals(Object obj) {
		return this.user_id.equals(((Item)obj).user_id);
	}
    
}